package com.woniuxy.orderservice.rabbit.consumer;


import com.woniuxy.core.status.OrderState;
import com.woniuxy.core.util.DateUtil;
import com.woniuxy.orderdao.model.Order;
import com.woniuxy.orderdao.model.OrderLog;
import com.woniuxy.orderservice.service.OrderService;
import com.woniuxy.util.MyAlipayUtil;
import com.woniuxy.util.PayInfoDto;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class CoachLongOrderConsumer {
    @Autowired
    private OrderService orderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MyAlipayUtil myAlipayUtil;

    @RabbitHandler
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = "coach-long-order-consumer"),
                    exchange = @Exchange(type = "direct", value = "coach-long-order-dead-ex"),
                    key = "coach-long-order-dead-key"
            )
    })
    public void coachLongOrderConsumer(String orderNum) throws Exception{
        Order orderInfo = orderService.getById(orderNum);
        if (orderInfo.getOrderState() == OrderState.CANCELED.getState()) return;
        PayInfoDto payInfoDto = myAlipayUtil.selectPayInfo(orderNum);
        if (!"TRADE_SUCCESS".equals(payInfoDto.getPayState())){
            orderInfo.setOrderState(OrderState.CANCELED.getState());
            orderService.updateById(orderInfo);
            //记录日志
            OrderLog log = new OrderLog();
            log.setLogUser("消息队列自动操作");
            log.setLogDesc("订单超时24小时未支付已取消");
            log.setLogTime(DateUtil.dateTimeToString(new Date()));
            log.setOrderNum(orderNum);
            rabbitTemplate.convertAndSend("order-log-queue",log);
        }

    }
}
